package com.gengzp.ops.service.impl;

import com.gengzp.common.exception.BusinessException;
import com.gengzp.common.model.database.entity.SysDatabase;
import com.gengzp.common.model.database.req.AddSysDatabaseReq;
import com.gengzp.common.model.database.req.EditSysDatabaseReq;
import com.gengzp.common.model.database.req.PageSysDatabaseReq;
import com.gengzp.common.model.database.resp.PageSysDatabaseResp;
import com.gengzp.common.model.database.resp.SearchSysDatabaseResp;
import com.gengzp.common.model.pagination.resp.PaginationResult;
import com.gengzp.ops.facade.IUserFacadeService;
import com.gengzp.ops.mapper.SysDatabaseMapper;
import com.gengzp.ops.service.ISysDatabaseService;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * @ClassName DatabaseServiceImpl
 * @Description 数据库管理模块服务层实现
 * @Author gengzp
 * @Date 2025/7/8 10:20
 */
@Service
public class SysDatabaseServiceImpl implements ISysDatabaseService {

    private static final Logger logger = LoggerFactory.getLogger(SysDatabaseServiceImpl.class);

    @Autowired
    private SysDatabaseMapper sysDatabaseMapper;

    @Autowired
    private IUserFacadeService userFacadeService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addSysDatabase(AddSysDatabaseReq req) {
        if (CollectionUtils.isNotEmpty(
                sysDatabaseMapper.selectByDatabaseCodeOrDatabaseName(req.getDatabaseCode(), req.getDatabaseName()))) {
            throw BusinessException.get("数据库已存在, 请勿重复添加");
        }

        SysDatabase sysDatabase = new SysDatabase();
        sysDatabase.setDatabaseName(req.getDatabaseName());
        sysDatabase.setDatabaseCode(req.getDatabaseCode());
        sysDatabase.setDatabaseUrl(req.getDatabaseUrl());
        sysDatabase.setDatabaseUsername(req.getDatabaseUsername());
        sysDatabase.setDatabasePassword(req.getDatabasePassword());
        sysDatabase.setDatabaseType(req.getDatabaseType());
        sysDatabase.setDatabaseDescription(req.getDatabaseDescription());
        sysDatabaseMapper.insertSysDatabase(sysDatabase);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editSysDatabase(EditSysDatabaseReq req) {
        SysDatabase sysDatabase = sysDatabaseMapper.selectById(Long.valueOf(req.getId()));
        if (Objects.isNull(sysDatabase)) {
            throw BusinessException.get("当前数据库不存在");
        }

        // 根据编码和名称查询数据库连接
        List<SysDatabase> sysDatabasesByCodeOrName = sysDatabaseMapper.selectByDatabaseCodeOrDatabaseName(
                req.getDatabaseCode(), req.getDatabaseName());
        if (CollectionUtils.isNotEmpty(sysDatabasesByCodeOrName) &&
                sysDatabasesByCodeOrName.stream().anyMatch(v -> !Objects.equals(v.getId(), sysDatabase.getId()))) {
            throw BusinessException.get("数据库名称或编码已存在, 无法编辑");
        }

        sysDatabase.setDatabaseName(req.getDatabaseName());
        sysDatabase.setDatabaseCode(req.getDatabaseCode());
        sysDatabase.setDatabaseUrl(req.getDatabaseUrl());
        sysDatabase.setDatabaseUsername(req.getDatabaseUsername());
        sysDatabase.setDatabasePassword(req.getDatabasePassword());
        sysDatabase.setDatabaseType(req.getDatabaseType());
        sysDatabase.setDatabaseDescription(req.getDatabaseDescription());
        sysDatabaseMapper.updateSysDatabaseById(sysDatabase);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSysDatabaseById(Long sysDatabaseId) {
        SysDatabase sysDatabase = sysDatabaseMapper.selectById(sysDatabaseId);
        if (Objects.isNull(sysDatabase)) {
            throw BusinessException.get("当前数据库不存在");
        }

        sysDatabaseMapper.deleteDatabaseById(sysDatabaseId);
    }

    @Override
    public PaginationResult<PageSysDatabaseResp> pageQuerySysDatabase(PageSysDatabaseReq req) {
        List<PageSysDatabaseResp> result = Lists.newArrayList();

        // 从数据库中分页查询出列表信息
        List<SysDatabase> sysDatabases = sysDatabaseMapper.pageQuerySysDatabase(req);
        if (CollectionUtils.isEmpty(sysDatabases)) {
            return PaginationResult.get(result, req);
        }

        // 转换数据类型为返回实体
        for (SysDatabase sysDatabase : sysDatabases) {
            PageSysDatabaseResp resp = new PageSysDatabaseResp();
            resp.setId(String.valueOf(sysDatabase.getId()));
            resp.setDatabaseName(sysDatabase.getDatabaseName());
            resp.setDatabaseCode(sysDatabase.getDatabaseCode());
            resp.setDatabaseUrl(sysDatabase.getDatabaseUrl());
            resp.setDatabaseType(sysDatabase.getDatabaseType());
            resp.setDatabaseDescription(sysDatabase.getDatabaseDescription());
            resp.setCreatedBy(String.valueOf(sysDatabase.getCreatedBy()));
            resp.setCreatedTime(sysDatabase.getCreatedTime());
            resp.setLastModifiedBy(String.valueOf(sysDatabase.getLastModifiedBy()));
            resp.setLastModifiedTime(sysDatabase.getLastModifiedTime());
            result.add(resp);
        }
        // 填充操作人信息
        userFacadeService.fillInOperatorInfo(result);

        return PaginationResult.get(result, req);
    }

    @Override
    public SearchSysDatabaseResp searchSysDatabaseById(Long sysDatabaseId) {
        SysDatabase sysDatabase = sysDatabaseMapper.selectById(sysDatabaseId);
        if (Objects.isNull(sysDatabase)) {
            throw BusinessException.get("当前数据库不存在");
        }

        SearchSysDatabaseResp resp = new SearchSysDatabaseResp();
        resp.setId(String.valueOf(sysDatabase.getId()));
        resp.setDatabaseName(sysDatabase.getDatabaseName());
        resp.setDatabaseCode(sysDatabase.getDatabaseCode());
        resp.setDatabaseUrl(sysDatabase.getDatabaseUrl());
        resp.setDatabaseUsername(sysDatabase.getDatabaseUsername());
        resp.setDatabasePassword(sysDatabase.getDatabasePassword());
        resp.setDatabaseType(sysDatabase.getDatabaseType());
        resp.setDatabaseDescription(sysDatabase.getDatabaseDescription());
        resp.setCreatedBy(String.valueOf(sysDatabase.getCreatedBy()));
        resp.setCreatedTime(sysDatabase.getCreatedTime());
        resp.setLastModifiedBy(String.valueOf(sysDatabase.getLastModifiedBy()));
        resp.setLastModifiedTime(sysDatabase.getLastModifiedTime());
        // 填充操作人信息
        userFacadeService.fillInOperatorInfo(resp);

        return resp;
    }

}
